package com.lzhl.buildjar.ui;

import com.lzhl.buildjar.ui.support.BaseDialog;
import com.lzhl.buildjar.ui.support.FileProvider;
import com.lzhl.buildjar.ui.support.JFileField;
import com.lzhl.buildjar.ui.support.Setting;
import com.lzhl.buildjar.util.ImageUtils;
import com.lzhl.buildjar.util.UIUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author 李柱良(@柱子的日月)
 * @date 2016/3/28
 */
public class SettingUI extends BaseDialog {
    //右边
    private JFileField tfClassPath;
    private JButton btnClassPath;
    private JButton btnClassPathPosition;

    private JButton btnOk;
    private JButton btnCancel;

    public SettingUI(Frame owner) {
        super(owner, "设置", true);

        jbinit();
        init();
        
        int width = (int) (owner.getSize().width * 0.8);
//          int height = (int) (owner.getSize().height * 0.6);
        setSize(width, 200);

        setResizable(true);
        setLocationRelativeTo(owner);
        setVisible(true);
    }

    private void jbinit() {
        Container container = getContentPane();
        container.setLayout(new BorderLayout());;

        //文件选择栏
        Box boxMain = Box.createVerticalBox();
        boxMain.setBorder(BorderFactory.createEmptyBorder(5, 4, 5, 4));
        container.add(boxMain, BorderLayout.CENTER);

        //类路径选择
        Box boxClassPath = Box.createHorizontalBox();
        boxClassPath.setAlignmentX(Component.LEFT_ALIGNMENT);
        boxClassPath.setMaximumSize(new Dimension(Integer.MAX_VALUE, 20));
        boxMain.add(boxClassPath);
        JLabel lb = new JLabel("默认类路径：");
        lb.setBorder(BorderFactory.createEmptyBorder(1, 4, 1, 0));
        boxClassPath.add(lb);
        tfClassPath = new JFileField(new FileProvider(true));
        boxClassPath.add(tfClassPath);
        btnClassPath = new JButton(ImageUtils.getImageIcon("browser.png"));
        btnClassPath.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 2));
        boxClassPath.add(btnClassPath);
        btnClassPathPosition = new JButton(ImageUtils.getImageIcon("location.png"));
        btnClassPathPosition.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 2));
        boxClassPath.add(btnClassPathPosition);
        btnClassPath.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFileChooser chooser = new JFileChooser();
                String classPath = tfClassPath.getText();
                if (classPath != null && classPath.trim().length() > 0) {
                    File dir = new File(classPath);
                    if (dir.isDirectory()) {
                        File parent = dir.getParentFile();
                        if (parent != null) {
                            chooser.setCurrentDirectory(parent);
                        } else {
                            chooser.setCurrentDirectory(dir);
                        }
                    } else {
                        File parent = dir.getParentFile();
                        if (parent != null) {
                            chooser.setCurrentDirectory(parent);
                        }
                    }
                }

                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int result = chooser.showOpenDialog(SettingUI.this);
                if (result == JFileChooser.APPROVE_OPTION) {
                    String filePath = chooser.getSelectedFile().getPath();
                    tfClassPath.setText(filePath);
                }
            }
        });
        btnClassPathPosition.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                File classPathDir = checkClassPath();
                explorerFile(classPathDir, false);
            }
        });


        Box boxCtrl = Box.createHorizontalBox();
        boxCtrl.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        boxCtrl.setPreferredSize(new Dimension(60, 40));
        boxCtrl.setMaximumSize(new Dimension(Integer.MAX_VALUE, 20));
        boxCtrl.setAlignmentX(Component.LEFT_ALIGNMENT);
        container.add(boxCtrl, BorderLayout.SOUTH);
        btnOk = new JButton("确定");
        btnCancel = new JButton("取消");
        boxCtrl.add(Box.createHorizontalGlue());
        boxCtrl.add(btnOk);
        boxCtrl.add(Box.createHorizontalStrut(5));
        boxCtrl.add(btnCancel);
    }

    private void init() {
        tfClassPath.setText(Setting.getClasspath());
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                tfClassPath.requestFocus();
            }
        });

        btnOk.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                btnOk_actionPerformed(e);
            }
        });

        btnCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
                dispose();
            }
        });
    }

    private void btnOk_actionPerformed(ActionEvent e) {
        UIUtils.invoke(new Runnable() {
            public void run() {
                Setting.setClasspath(tfClassPath.getText());
            }
        });

        setVisible(false);
        dispose();
    }

    private File checkClassPath() {
        String classPath = tfClassPath.getText();
        if (classPath == null || classPath.trim().length() == 0) {
            JOptionPane.showMessageDialog(this, "类路径没有设置！");
            tfClassPath.requestFocus();
            return null;
        }
        File classPathDir = new File(classPath.trim());
        if (!classPathDir.isDirectory()) {
            JOptionPane.showMessageDialog(this, "类路径设置有误！");
            tfClassPath.requestFocus();
            return null;
        }
        return classPathDir;
    }

    private void explorerFile(File file, boolean select) {
        if(file != null) {
            try {
                String command = "explorer ";
                if(select) {
                    command += "/select, ";
                }
                command += file.getAbsolutePath();
                Runtime.getRuntime().exec(command);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    @Override
    protected boolean canExit() {
        if(tfClassPath.isSuggesting()) {
            return false;
        }
        return super.canExit();
    }
}
